package cn.zhangyong.dbframelearn.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.zhangyong.dbframelearn.bean.Author;
import cn.zhangyong.dbframelearn.db.DBHelper;

/**
 * description:
 * autour: zhangyong
 * date: 2019/4/3 10:27
 * update: 2019/4/3
 * version:
 */
public class AuthorDao {
    private Dao<Author,Integer> authorDao;
    private DBHelper dbHelper;

    public AuthorDao(Context context){
        dbHelper = DBHelper.getInstance(context);
        try {
            authorDao = dbHelper.getDao(Author.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加一条记录
     * @param author
     */
    public void add(Author author){
        try {
            authorDao.createOrUpdate(author);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一条记录
     * @param author
     */
    public void delete(Author author){
        try {
            authorDao.delete(author);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新一条记录
     * @param author
     */
    public void update(Author author){
        try {
            authorDao.update(author);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询一条记录
     * @param name
     * @return
     */
    public Author queryForName(String name){
        try {
            List<Author> authors = authorDao.queryForEq("name",name);
            if(authors != null && authors.size()>0){
                Author author = authors.get(0);
                return author;
            }else{
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查找出现异常.");
        }
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<Author> queryForAll(){
        List<Author> authors = new ArrayList<>();
        try {
            authors = authorDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return authors;
    }

    public boolean isAuthorExit(String name){
        List<Author> authors = null;
        try {
            authors = authorDao.queryForEq("name",name);
            if(authors != null && authors.size() == 1){
                return true;
            }else{
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查找用户异常.");
        }
    }
}
